package cn.wolfcode.shop.cloud.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by wolfcode-lanxw
 */
@Slf4j
public class CommonControllerAdvice {

    private CodeMsg defaultErrorMsg;
    private CodeMsg argsErrorMsg;

    protected CommonControllerAdvice() {
        this(CodeMsg.DEFAULT_ERROR, CodeMsg.DEFULT_ARGS_ERROR);
    }

    protected CommonControllerAdvice(CodeMsg defaultErrorMsg, CodeMsg argsErrorMsg) {
        this.defaultErrorMsg = defaultErrorMsg;
        this.argsErrorMsg = argsErrorMsg;
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result hanldeBusinessException(BusinessException ex){
        return Result.error(ex.getCodeMsg());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handleException(Exception e){
        log.error("[异常处理] 服务端其他异常", e);
        return Result.error(defaultErrorMsg);
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result handleException(BindException e){
        // 当前校验失败的第一个校验失败错误提示
        ObjectError error = e.getAllErrors().get(0);
        // 贴在注解上真正需要提示用户的消息
        String message = error.getDefaultMessage();
        // 为了防止多线程共同修改一个对象导致冲突
        CodeMsg codeMsg = new CodeMsg(argsErrorMsg.getCode(), message);
        return Result.error(codeMsg);
    }
}
